package org.beian.fmmall.controller;

import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import org.beian.fmmall.service.OrderService;
import org.beian.fmmall.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Api(tags = "支付回调管理")
public class PayController {
    @Autowired
    private OrderService orderService;
    @RequestMapping("/success")
    public String success(HttpServletRequest request) throws Exception {
        System.out.println("---------paysuccess");
        ServletInputStream is = request.getInputStream();
        byte[] bs=new byte[1024];
        StringBuilder builder = new StringBuilder();
        int len=-1;
        while ((len=is.read(bs))!=-1){
            builder.append(new String(bs, 0, len));
        }
        String s = builder.toString();
        Map<String, String> map = WXPayUtil.xmlToMap(s);
        if(map!=null&&"success".equalsIgnoreCase(map.get("result_code"))){
            //支付成功
            //修改支付状态，待发货\已支付
            int i = orderService.updateOrderStatus(map.get("out_trade_no"), "2");
            if(i>0){
                WebSocketServer.sendMsg(map.get("out_trade_no"),"1");
                //响应微信支付平台
                HashMap<String,String> resp=new HashMap<>();
                resp.put("return_code","success");
                resp.put("return_msg","OK");
                resp.put("appid",map.get("appid"));
                resp.put("result_code","success");
                return WXPayUtil.mapToXml(resp);
            }
        }
        return null;
    }
}
